package main

import (
	"bc/dao"
	"bc/route"
	. "bc/util"
	"context"
	"golang.org/x/sync/errgroup"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

var g errgroup.Group

func init(){
	dao.InitDb()
}

func main(){

	//restful api
	iniRoute := route.InitRouter()
	api := &http.Server{
		Addr:Config.Server.HttpPort,
		Handler:iniRoute,
		ReadTimeout:Config.Server.ReadTimeout * time.Second,
		WriteTimeout:Config.Server.WriteTimeout * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	//静态页
	htmlRoute := route.HtmlHander()
	html := &http.Server{
		Addr:Config.Server.HtmlHttpPort,
		Handler:htmlRoute,
		ReadTimeout:Config.Server.ReadTimeout * time.Second,
		WriteTimeout:Config.Server.WriteTimeout * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	g.Go(func() error {
		return api.ListenAndServe()
	})

	g.Go(func() error {
		return html.ListenAndServe()
	})
	if err := g.Wait(); err != nil {
		panic(err)
	}

	//优雅关闭
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := html.Shutdown(ctx); err != nil {
		log.Fatal("Html Server Shutdown:", err)
	}
	if err := api.Shutdown(ctx);err != nil{
		log.Fatal("Api Server Shutdown:",err)
	}
	log.Println("Server exiting")
}
